#include "plurkauthview.h"
#include <QtDebug>
#include <QWebFrame>
#include <QWebView>
#include <QWebPage>

PlurkAuthView::PlurkAuthView(QWidget *parent) :
    QWidget(parent), webView(this)
{
  connect(&webView, SIGNAL(loadFinished(bool)),
          this, SLOT(pageFinished(bool)));
  connect(&webView, SIGNAL(loadProgress(int)),
          this, SLOT(loadProgress(int)));

  statusBar.setText("Please login into Plurk to authenticated the MeeGo Plurker");
  statusBar.setAutoFillBackground(true);
  statusBar.setFrameStyle(QFrame::Panel | QFrame::Sunken);
  layout.setSpacing(0);
  layout.setContentsMargins(0, 0, 0, 0);
  layout.addWidget(&webView); 
  layout.addWidget(&statusBar); 
  setLayout(&layout);

}

void PlurkAuthView::openAuth(const QUrl &url)
{
  authInitUrl = url;
  webView.load(url);
}

void PlurkAuthView::loadProgress(int progress)
{
//  statusBar.setText("Loading " + QString::number(progress) + "%");
}

void PlurkAuthView::pageFinished(bool ok)
{
  if (webView.url().toString().indexOf("/m/authorize?oauth_token") > -1) {
    setVisible(true);
    return;
  }
  if (webView.url().toString() == "http://www.plurk.com/OAuth/authorizeDone") {
    QString _verify = "";
    QString str = webView.page()->currentFrame()->toHtml();
    QRegExp rx("( <b>)([0-9]+)(</b><br>)");
    int pos = 0;
    while ((pos = rx.indexIn(str, pos)) != -1) {
      _verify = rx.cap(2);
      pos += rx.matchedLength();
    }

    emit authDone(_verify.length() > 0, _verify);
    return;
  }
}
